<template>
  <div class="uploadPhoto">
    <el-upload
      :action="action"
      list-type="picture-card"
      :before-upload="handleBeforeUpload"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      accept=".jpeg,.jpg,.png"
      :limit="limit"
      :file-list="files"
      :class="{ disabledImg: files.length == limit ? true : false }"
    >
      <i class="el-icon-plus"></i>
      <div class="el-upload__text">{{ uploadText }}</div>
      <div class="el-upload__tip" slot="tip">
        {{ uploadTip }}
      </div>
    </el-upload>
  </div>
</template>

<script>
import uploadDomain from "@/utils/uploadDomain";

export default {
  name: "",
  props: {
    uploadText: {
      type: String,
      default: "上传图片",
    },
    uploadTip: {
      type: String,
      default: "请上传小于10MB的图片，支持jpg/png格式，最多上传1张",
    },
    limit: {
      type: Number,
      default: 1,
    },
    //数据回显
    fileList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      action: `${uploadDomain}backend/upload/upload`,
      files: [],
    };
  },

  components: {},

  computed: {},

  beforeMount() {},

  mounted() {
    // console.log(this.fileList, ">><<<>>>RRRRR---this.fileList");
  },

  methods: {
    handleBeforeUpload(file) {
      if (file.size > 1048576 * 10) {
        this.$message.warning("请上传小于10MB的图片");
        return false;
      }
      const suffix = file.name?.slice(file.name?.lastIndexOf(".") + 1);
      const reg = /jpg|png/i;
      if (!reg.test(suffix)) {
        this.$message.warning("仅支持jpg、png格式的图片！");
        return false;
      }
    },
    handlePreview() {},
    handleRemove(file) {
      console.log(this.files);
      const findex = this.files.findIndex((item) => item.url == file.url);
      if (findex > -1) {
        this.files.splice(findex, 1);
        this.$emit("onSuccess", this.files);
        // this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$message.warning(`最多上传${this.limit}张`);
    },
    handleSuccess(res, file, fileList) {
      console.log(res, ">>>>>>res===");
      this.files.push({
        name: res.data,
        url: this.$resDomain + res.data,
      });
      this.$emit("onSuccess", this.files);

      //   this.files.push();
    },
  },

  watch: {
    fileList: {
      handler(newVal) {
        this.files = [...newVal];
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.uploadPhoto {
  /deep/.el-upload {
    position: relative;
  }
  /deep/.disabledImg {
    .el-upload--picture-card {
      display: none;
    }
  }
  .el-upload__text {
    padding-top: 30px;
    width: 100%;
    position: absolute;
    left: 0;
    top: 0px;
    font-size: 16px;
    color: #b7b7b7;
  }
}
</style>
